package com.xinongbest.mall.filter;

import com.xinongbest.mall.common.Constant;
import com.xinongbest.mall.model.pojo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lemonwan
 * 用户登录过滤器
 */
public class UserFilter implements Filter {

    public static User currentUser;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        currentUser = (User) httpServletRequest.getSession().getAttribute(Constant.IMOOC_MALL_USER);
        if (currentUser == null) {
            PrintWriter writer = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            writer.write("{\"status\":\"10007\",\"msg\":\"NEED_LOGIN\",\"data\": null}");
            writer.flush();
            writer.close();
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
